const { ccclass, property } = cc._decorator;

interface itemData {
    num: number,         //编号
    zIndex: number,
    scale: number,
    opacity: number,
    position: cc.Vec2,
}
//数组个数和顺序需要统一
const zIndexGrp = [0, 2, 4, 5, 3, 1]                   //zIndex数组
const scaleGrp = [0.4, 0.5, 0.8, 1, 0.8, 0.5]          //大小数组
const opacityGrp = [255, 255, 255, 255, 255, 255]      //透明度数组
const posGrp = [cc.v2(0, 0), cc.v2(-300, 0), cc.v2(-200, 0), cc.v2(0, 0), cc.v2(200, 0), cc.v2(300, 0)]    //6个位置数组

@ccclass
export default class ShufflingFigure extends cc.Component {
    @property(cc.Node)
    touchNode: cc.Node = null //触摸滑动判定区域    
    @property(cc.Node)
    content: cc.Node = null   //添加item的父节点
    @property(cc.Float)
    moveTime: number = 0.3
    @property(cc.Boolean)
    isCycle: boolean = true

    tweenGrp: cc.Tween[] = []
    isMoving: boolean = false
    cardsArray: cc.Node[] = []                  //content的子节点
    pageGrp: any[] = []                         //所有的页面信息
    pageStartServer: Function = null            //点击或者滑动前需要调用的函数
    pageEndServer: Function = null               //翻页结束页面更新的
    pageIndex: number = -1
    pageInfoUpdateServer: Function = null          //更新每一个item的方法
    itemInfoGrp: itemData[] = []                //6个item 位置的信息
    firstX: number = 0                          //触摸时x
    firstY: number = 0                          //触摸时y
    nodeMap: Map<number, cc.Node> = new Map()
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {
    }


    itemInfoGrpInit() {
        for (let i = 0; i < this.content.children.length; i++) {
            let info: itemData = { num: i, zIndex: zIndexGrp[i], scale: scaleGrp[i], opacity: opacityGrp[i], position: posGrp[i] }
            this.itemInfoGrp.push(info)
        }
    }
    // update (dt) {},

    /**
     * 
     * @param {*} pageIndex 初始化index
     * @param {*} pageGrp page的数组信息，所有页面初始化所要传入的信息
     * @param {*} pageStartServer page点击或者滑动前调用方法
     * @param {*} pageEndServer page翻页结束后页面信息更新方法
     * @param {*} pageInfoUpdateServer 初始化pageitem 方法
     */
    structPageInit(pageIndex?: number, pageGrp?: Array<any>, pageStartServer?: Function, pageEndServer?: Function, pageInfoUpdateServer?: Function) {
        this.pageIndex = pageIndex
        this.clearTweenGrp()
        this.itemInfoGrpInit()
        this.isMoving = false
        this.tweenGrp = []
        if (pageGrp) {
            this.pageGrp = pageGrp
        }
        if (pageStartServer) {
            this.pageStartServer = pageStartServer
        }
        if (pageEndServer) {
            this.pageEndServer = pageEndServer
        }
        if (pageIndex >= 0) {
            this.pageIndex = pageIndex
        }
        if (pageInfoUpdateServer) {
            this.pageInfoUpdateServer = pageInfoUpdateServer
        }
        this.cardsArray = this.content.children;

        for (let i = 0; i < this.cardsArray.length; i++) {
            this.cardsArray[i].getChildByName('New Label').getComponent(cc.Label).string = `${i}`
            this.setNodeInfo(i, i)
        }
        this.touchListen()
        // this.fivePageInfoInit(this.pageIndex)
        if (this.pageEndServer) {
            this.pageEndServer()
        }
    }


    setNodeInfo(i: number, index: number) {
        this.cardsArray[i].zIndex = this.itemInfoGrp[index].zIndex
        this.cardsArray[i].scale = this.itemInfoGrp[index].scale;
        this.cardsArray[i].opacity = this.itemInfoGrp[index].opacity;
        this.cardsArray[i].setPosition(this.itemInfoGrp[index].position)
        this.nodeMap.set(index, this.cardsArray[i])
    }

    //滑动监听
    touchListen() {
        this.touchNode.on(cc.Node.EventType.TOUCH_START, this.touchStartServer, this)
        this.touchNode.on(cc.Node.EventType.TOUCH_END, this.touchEndServer, this)
        this.touchNode.on(cc.Node.EventType.TOUCH_CANCEL, this.touchCancelServer, this)
    }
    //关闭监听
    closeTouchListen() {
        this.touchNode.targetOff(this)
        for (let i = 0; i < this.tweenGrp.length; i++) {
            if (this.tweenGrp[i]) {
                this.tweenGrp[i].stop()
                this.tweenGrp[i] = null
            }
        }
    }
    //触摸开始
    touchStartServer(event) {
        let location = event.getLocation();// 获取节点坐标
        this.firstX = location.x;
        this.firstY = location.y;
    }
    //触摸结束
    touchEndServer(event) {
        let touchPoint = event.getLocation();
        let endX = this.firstX - touchPoint.x;

        if (endX > 5) {
            //向左函数
            // console.log('left');
            this.revolve2Left()
        } else if (endX < -5) {
            //向右函数
            // console.log('right');
            this.revolve2Right()
        }
    }
    //取消触摸
    touchCancelServer(event) {
        let touchPoint = event.getLocation();
        let endX = this.firstX - touchPoint.x;
        let endY = this.firstY - touchPoint.y;

        if (endX > 5) {
            //向左函数
            this.revolve2Left()
        } else {
            //向右函数
            this.revolve2Right()
        }
    }

    //页面初始化
    fivePageInfoInit(index) {
        let inputIndex = this.pageIndex
        if (index >= 0) {
            inputIndex = index
        }
        this.pageInfoUpdateServer(0, this.pageGrp[inputIndex])
        if (inputIndex - 1 >= 0) {
            this.pageInfoUpdateServer(this.content.children.length - 1, this.pageGrp[inputIndex - 1])
        } else {
            this.pageInfoUpdateServer(this.content.children.length - 1, null)
        }
        if (inputIndex - 2 >= 0) {
            this.pageInfoUpdateServer(this.content.children.length - 2, this.pageGrp[inputIndex - 2])
        } else {
            this.pageInfoUpdateServer(this.content.children.length - 2, null)
        }
        if (inputIndex + 1 <= this.pageGrp.length - 1) {
            this.pageInfoUpdateServer(1, this.pageGrp[inputIndex + 1])
        } else {
            this.pageInfoUpdateServer(1, null)
        }
        if (inputIndex + 2 <= this.pageGrp.length - 1) {
            this.pageInfoUpdateServer(2, this.pageGrp[inputIndex + 2])
        } else {
            this.pageInfoUpdateServer(2, null)
        }
        // console.log(this.pageGrp[inputIndex - 2], this.pageGrp[inputIndex - 1], this.pageGrp[inputIndex], this.pageGrp[inputIndex + 1], this.pageGrp[inputIndex + 2])
    }



    //往右转一格 
    revolve2Right() {
        if (this.isMoving) {
            return
        }
        // 往右旋转
        if (this.pageStartServer) {
            this.pageStartServer(false)
        }
        this.isMoving = true

        let map: Map<number, cc.Node> = new Map()
        this.nodeMap.forEach((value, key) => {
            let target = key
            if (key == (this.cardsArray.length - 1)) {
                target = 0
            } else {
                target += 1
            }
            map.set(target, value)
            let nextAttr = this.itemInfoGrp[target];
            value.zIndex = nextAttr.zIndex;
            this.tweenGrp[key] = cc.tween(value)
                .to(this.moveTime, { position: cc.v3(nextAttr.position, 0), scale: nextAttr.scale, opacity: nextAttr.opacity })
                .call(() => {
                    this.isMoving = false
                    if (this.pageEndServer) {
                        this.pageEndServer()
                    }
                })
                .start()

        })
        this.nodeMap = map
    }
    //往左转一格
    revolve2Left() {
        if (this.isMoving) {
            return
        }
        // 往左旋转
        if (this.pageStartServer) {
            this.pageStartServer(true)
        }
        this.isMoving=true
        let map: Map<number, cc.Node> = new Map()
        this.nodeMap.forEach((value, key) => {
            let target = key
            if (key == 0) {
                target = (this.cardsArray.length-1)
            } else {
                target -= 1
            }
            map.set(target, value)
            let nextAttr = this.itemInfoGrp[target];
            value.zIndex = nextAttr.zIndex;
            this.tweenGrp[key] = cc.tween(value)
                .to(this.moveTime, { position: cc.v3(nextAttr.position, 0), scale: nextAttr.scale, opacity: nextAttr.opacity })
                .call(() => {
                    this.isMoving = false
                    if (this.pageEndServer) {
                        this.pageEndServer()
                    }
                })
                .start()

        })
        this.nodeMap = map
       
    }
    //动画取消
    clearTweenGrp() {
        if (this.tweenGrp) {
            for (let i = 0; i < this.tweenGrp.length; i++) {
                if (this.tweenGrp[i]) {
                    this.tweenGrp[i].stop()
                    this.tweenGrp[i] = null
                }
            }
        }
    }
}
